/** @file
  A Dxe Timer Library implementation which uses the Time Stamp Counter in the processor.
  This instance will use ACPI timer to calculate TSC frequency.

@copyright
 Copyright (c) 2011 - 2017 Intel Corporation. All rights reserved
 This software and associated documentation (if any) is furnished
 under a license and may only be used or copied in accordance
 with the terms of the license. Except as permitted by the
 license, no part of this software or documentation may be
 reproduced, stored in a retrieval system, or transmitted in any
 form or by any means without the express written consent of
 Intel Corporation.
 This file contains 'Framework Code' and is licensed as such
 under the terms of your license agreement with Intel or your
 vendor. This file may not be modified, except as allowed by
 additional terms of your license agreement.

@par Specification Reference:
**/

#include <PiDxe.h>
#include <Library/UefiBootServicesTableLib.h>
#include <Library/UefiLib.h>
#include <Library/DebugLib.h>
#include <Guid/TscFrequency.h>
#include "TscTimerLibInternal.h"

UINT64 mTscFrequency = 0;   // RPPO-SKL-0005

/** The constructor function determines the actual TSC frequency.

  First, Get TSC frequency from system configuration table with TSC frequency GUID,
  if the table is not found, install it.
  This function will always return EFI_SUCCESS.

  @param[in]  ImageHandle       The firmware allocated handle for the EFI image.
  @param[in]  SystemTable       A pointer to the EFI System Table.

  @retval     EFI_SUCCESS       The constructor always returns EFI_SUCCESS.

**/
EFI_STATUS
EFIAPI
DxeTscTimerLibConstructor (
  IN EFI_HANDLE        ImageHandle,
  IN EFI_SYSTEM_TABLE  *SystemTable
  )
{
  EFI_STATUS  Status;
  UINT64      *TscFrequency;

  //
  // Get TSC frequency from system configuration table with TSC frequency GUID.
  //
  Status = EfiGetSystemConfigurationTable (&gEfiTscFrequencyGuid, (VOID **) &TscFrequency);
  if (Status == EFI_SUCCESS) {
    mTscFrequency = *TscFrequency;
    return EFI_SUCCESS;
  }

  //
  // TSC frequency GUID system configuration table is not found, install it.
  //

  Status = gBS->AllocatePool (EfiBootServicesData, sizeof (UINT64), (VOID **) &TscFrequency);
  ASSERT_EFI_ERROR (Status);

  *TscFrequency = InternalCalculateTscFrequency ();
  //
  // TscFrequency now points to the number of TSC counts per second, install system configuration table for it.
  //
  gBS->InstallConfigurationTable (&gEfiTscFrequencyGuid, TscFrequency);

  mTscFrequency = *TscFrequency;
  return EFI_SUCCESS;
}

/**  Get TSC frequency.

  @return The number of TSC counts per second.

**/
UINT64
InternalGetTscFrequency (
  VOID
  )
{
//
// RPPO-SKL-0005: RoyalParkOverrideBegin
//
  if (mTscFrequency == 0) {
    mTscFrequency = InternalCalculateTscFrequency ();
  }
//
// RPPO-SKL-0005: RoyalParkOverrideEnd
//

  return mTscFrequency;
}

